import { onMounted, onUnmounted } from "vue";
// 定义类型
type ScrollCallBack = (scorllTop: number) => void;

export function usePageScroll(callback: ScrollCallBack, throttleTime = 100) {
  let timer: ReturnType<typeof setTimeout> | null = null;

  // 节流处理
  const handleScroll = (event: { scrollTop: number }) => {
    if (timer) {
      timer = setTimeout(() => {
        callback(event.scrollTop);
        timer = null;
      }, throttleTime);
    }
  };

  // 监听页面滚动
  onMounted(() => {
    uni.pageScrollTo = () => {};
    // uni.pageScrollTo?.(handleScroll);
    // uni.pageScrollTo({
    //   scrollTop: 0,
    //   duration: 0,
    //   success: () => {
    //     // 正确监听滚动事件
    //     uni.onPageScroll(handleScroll as (res: any) => void);
    //   },
    // });
  });

  onUnmounted(() => {
    if (timer) clearTimeout(timer);
  });
}
